package com.ybwh.springboot1.conf;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

@Configuration
public class MybatisPlusConfig {



	@Bean("sqlSessionFactory")
	public MybatisSqlSessionFactoryBean createSqlSessionFactoryBean(@Autowired DataSource dataSource)
			throws IOException {
		MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
		sqlSessionFactoryBean.setTypeAliasesPackage("com.ybwh.**.model.**");

		GlobalConfig globalConfig = new GlobalConfig();
		DbConfig  dbConfig= new DbConfig();
		globalConfig.setDbConfig(dbConfig);
		// 主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
		dbConfig.setIdType(IdType.NONE);
		// 字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
		dbConfig.setFieldStrategy(FieldStrategy.IGNORED);
		dbConfig.setDbType(DbType.MYSQL);
		sqlSessionFactoryBean.setGlobalConfig(globalConfig);

		MybatisConfiguration configuration = new MybatisConfiguration();
		// #配置返回数据库(column下划线命名&&返回java实体是驼峰命名)，自动匹配无需as（没开启这个，SQL需要写as： select user_id
		// as userId）
		configuration.setMapUnderscoreToCamelCase(true);
		configuration.setCacheEnabled(false);
		//分页插件
		configuration.addInterceptor(new PaginationInterceptor());
		sqlSessionFactoryBean.setConfiguration(configuration);
		

		return sqlSessionFactoryBean;

	}

	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
		mapperScannerConfigurer.setBasePackage("com.ybwh.**.dao");

		return mapperScannerConfigurer;
	}

}